﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Mvc;
using wtmimtdemo.Models;
using wtmimtdemo.Models.LayuiIM;
using wtmimtdemo.SignalRHub.ConectionOperate;

namespace wtmimtdemo.Areas.LauiIm.Controllers
{
    [AuthorizeJwtWithCookie]
    [ApiController]
    [Route("api/[controller]/[action]")]
    [ActionDescription("imapi控制器")]
    [AllRights]
    public class ImInfoController : BaseApiController
    {
        [HttpGet]
        public async Task<IActionResult> GetinitData()
        {

            var userinfo = await DC.Set<FrameworkUser>().AsNoTracking().FirstOrDefaultAsync(x => x.ID == new Guid(Wtm.LoginUserInfo.UserId));

            ImUserInfo mineinfo = new()
            {
                username = Wtm.LoginUserInfo.Name,
                id = Wtm.LoginUserInfo.UserId,
                status = "online",
                avatar = Wtm.LoginUserInfo.PhotoId != null ? "/api/_file/getuserphoto/" + Wtm.LoginUserInfo.PhotoId : "",
                sign = userinfo.Sign,

            };
            var conn = ConnectionManagement.SignalRConns;
            var unitworks = await DC.Set<UnitWork>().AsNoTracking().ToListAsync();
            List<FriendInfo> FriendInfos = new();
            unitworks.ForEach(async work =>
            {
                FriendInfo friendInfo = new();
                friendInfo.groupname = work.DepName;
                friendInfo.id = work.ID.ToString();
                var users = await DC.Set<FrameworkUser>().AsNoTracking()
                .Where(user => user.UnitWorkId == work.ID)
                .Select(user => new ImUserInfo
                {
                    username = user.Name,
                    id = user.ID.ToString().ToLower(),
                    status = ConnectionManagement.IsConn(user.ID.ToString()) == true ? "online" : "offline",
                    avatar = user.PhotoId!=null?"/api/_file/getuserphoto/" + user.PhotoId:"",
                    sign = user.Sign,

                })
                .ToListAsync();
                friendInfo.list = users;
                FriendInfos.Add(friendInfo);

            });

            var imInitUserData = new ImInitUserData
            {
                mine = mineinfo,
                friend = FriendInfos
            };

            ImInitData initData = new()
            {
                code = 0,
                msg = "",
                data = imInitUserData
            };

            return Ok(initData);


        }
    }
}
